package com.sangmo.fts.process.storage.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.boot.framework.data.filter.PageResult;
import com.sangmo.boot.framework.data.filter.PageSearch;
import com.sangmo.boot.framework.data.filter.ValueFilter;
import com.sangmo.boot.framework.plugin.dataview.crud.service.DelegateViewService;
import com.sangmo.boot.framework.plugin.dataview.crud.service.ViewService;
import com.sangmo.fts.process.storage.model.CsfStock;
import com.sangmo.fts.process.storage.model.CsfStockItem;
import com.sangmo.fts.process.storage.model.CsfWaybillItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class CsfStockService extends DelegateViewService<CsfStock> {

    @Autowired
    private CsfStockEntityService csfStockEntityService;

    @Autowired
    private CsfStockItemEntityService csfStockItemEntityService;

    @Override
    protected ViewService<CsfStock> getEntityService() {
        return csfStockEntityService;
    }

    public void submit(Long id) {
        CsfStock stock = this.get(id);
        if (null == stock.getConfirmDoc() || !CsfStock.States.SUBMITTING.equals(stock.getState())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.csfStock.submit.state.wrong");
        }
        stock.setState(CsfStock.States.PENDING);
        this.save(stock);
    }

    public void confirm(Long id) {
        CsfStock stock = this.get(id);
        if (!CsfStock.States.PENDING.equals(stock.getState())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.csfStock.confirm.state.wrong");
        }
        stock.setState(CsfStock.States.CONFIRMED);
        this.save(stock);
    }

    public PageResult<CsfStockItem> listItemsByPage(Long stockId, PageSearch ps) {
        ps.getFilters().add(new ValueFilter("stockId", ValueFilter.OP_EQ, stockId));
        return csfStockItemEntityService.search(ps);
    }



}
